<template>
  <div class="home">
    <div class="wCen">
      <h2 class="title">代购助手</h2>
      <van-field
        v-model="value"
        rows="1"
        type="textarea"
        maxlength="200"
        placeholder="请粘贴地址信息"
      >
        <template #button>
          <van-button size="small" type="warning" @click="order">代购</van-button>
        </template>
      </van-field>
      <p>请将地址信息粘贴于上面的输入框，点击“代购”进行代购操作</p>
    </div>
  </div>
</template>

<script>
import { Toast, Dialog } from "vant";
export default {
  data() {
    return {
      value: "",
      // 飞机
      // https://item.taobao.com/item.htm?id=751242805639&ns=1&abbucket=19#detail
      // 靴子
      // https://item.taobao.com/item.htm?id=742955723361
    };
  },
  computed: {
    id() {
      return this.getId(this.value);
    },
  },
  mounted() {
    this.getClipboardContent();
  },
  methods: {
    /**
     * 获取地址输入地址的id如果返回undefined则地址不合法
     * @example https://item.taobao.com/item.htm?id=751242805639&ns=1&abbucket=19#detail
     * @returns 751242805639
     */
    getId(propsUrl) {
      try {
        const url = new URL(propsUrl);
        if (["item.taobao.com"].includes(url.hostname)) {
          const id = url.searchParams.get("id");
          if (id) {
            return id;
          }
        }
      } catch (error) {}
      return undefined;
    },
    // 获取剪贴板内容
    getClipboardContent() {
      Dialog.confirm({
        title: "标题",
        message: "是否同意使用获取剪贴板内容？",
      })
        .then(() => {
          if (navigator.clipboard) {
            navigator.clipboard
            .readText()
            .then((res) => {
              console.log("剪切板内容:", res);
              this.value = res;
              this.order();
            })
            .catch((err) => {
              console.log("获取剪切板内容失败:", err);
            });
          }
        })
        .catch(() => {
          // on cancel
        });
    },
    order() {
      console.log("id:",this.id)
      if (this.id) {
        this.$router.push({
          path: `/detail?id=${this.id}`,
        });
      } else {
        Toast.fail("内容格式有误");
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.home {
  min-height: 100vh;
  .title {
    font-size: 16px;
    text-align: center;
  }
}
</style>
